package com.my.socket.nio.v33;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by ZhongGang
 * at 2018/8/24 15:45
 */
public class Poller implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(Poller.class);

    private Selector selector;
    private BlockingQueue<SocketChannel> queue;
    private AtomicInteger wakeup = new AtomicInteger(0);
    private ByteBuffer readBuffer = ByteBuffer.allocate(512);
    private ByteBuffer writeBuffer = ByteBuffer.allocate(512);

    public Poller() throws Exception {
        this.selector = Selector.open();
        this.queue = new LinkedBlockingDeque<>();
    }

    public void put(SocketChannel socketChannel) throws InterruptedException {
        this.queue.put(socketChannel);
        if (wakeup.incrementAndGet() == 0) {
            this.selector.wakeup();
        }
    }

    @Override
    public void run() {
        while (!Thread.interrupted()) {
            try {
                SocketChannel socketChannel;
                while ((socketChannel = this.queue.poll()) != null) {
                    socketChannel.register(this.selector, SelectionKey.OP_READ);
                }

                if (wakeup.getAndSet(-1) > 0) {
                    this.selector.selectNow();
                } else {
                    this.selector.select(1000);
                }
                this.wakeup.set(0);

                Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();

                    SocketChannel sock = (SocketChannel) selectionKey.channel();
                    sock.read(this.readBuffer);
                    String request = new String(this.readBuffer.array(), 0, this.readBuffer.position());
                    LOGGER.info("read: {}", request);

                    String response = request.toUpperCase();
                    this.writeBuffer.put(response.getBytes());
                    this.writeBuffer.flip();
                    sock.write(writeBuffer);
                    LOGGER.info("write: {}", response);

                    this.readBuffer.clear();
                    this.writeBuffer.clear();
                    sock.close();
                }
            } catch (Exception e) {
                LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
            }
        }
    }
}
